<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图区域-->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>

      <el-table :data="roleList" border  stripe style="width: 100%">
        <el-table-column type="expand">
          <!--作用域插槽-->
          <template slot-scope="scope">
            <el-row :class="['vcenter','bdbottom',i1===0?'bdtop':'']" :key="item1.index" v-for="(item1,i1) in scope.row.children">
              <!--渲染一级权限-->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col >
              <!--渲染二 三级权限-->
              <el-col :span="19">
                <!--通过for循环嵌套循环二级权限-->
                <el-row :class="[i2===0?'':'bdtop','vcenter']" :key="item2.index" v-for="(item2,i2) in item1.children">
                  <!--二级-->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                      {{item2.authName}}
                      <i class="el-icon-caret-right"></i>
                    </el-tag>
                  </el-col>
                  <!--三级-->
                  <el-col :span="18">
                    <el-tag type="warning" :key="item3.index" v-for="(item3,i3) in item2.children"
                            closable @close="removeRightById(scope.row,item3.id)">
                      {{item3.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--
            <pre>
            {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column  label="操作" width="300px">
          <template slot-scope="scope">
            <!--编辑-->
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <!--删除-->
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <!--分配权限-->
            <el-button type="warning" icon="el-icon-setting" size="mini"
             @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[3, 5, 10, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--分配权限对话框-->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="clearRightsKey">
      <!--内容主体区域,树形控件-->
      <el-tree :data="rightsList" :props="defaultProps" show-checkbox
               node-key="id" :default-checked-keys="defKeys" default-expand-all></el-tree>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRightDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <!--增加权限操作-->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules"  ref="addFormRef"
               label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.rolename"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roledesc"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const temproleList=[
    {
      id:1,
      roleName:'管理员',
      roleDesc:'全局管理员',
      children:[
        {
          id: '101',
          authName: '商品管理',
          path: null,
          children: [
            {
              id: '10101',
              authName: '商品列表',
              path: null,
              children: [
                {
                  id: '1010101',
                  authName: '添加商品',
                  path: null
                }, {
                  id: '1010102',
                  authName: '修改商品',
                  path: null
                }, {
                  id: '1010103',
                  authName: '删除商品',
                  path: null
                }, {
                  id: '1010104',
                  authName: '商品状态更新',
                  path: null
                }
              ]
            },{
              id: '10102',
              authName: '商品分类',
              path: null,
              children: [
                {
                  id: '1010201',
                  authName: '分类管理',
                  path: null
                }
              ]
            },{
              id: '10103',
              authName: '商品参数',
              path: null,
              children: [
                {
                  id: '1010301',
                  authName: '参数管理',
                  path: null
                }
              ]
            }
          ]
        },
        {id: '102',
          authName:'订单管理',
          path:null,
          children: [
            {
              id: '10201',
              authName:'订单列表',
              path:null,
              children: [
                {
                  id: '1020101',
                  authName:'添加订单',
                  path:null
                }
              ]
            }
          ],
        },
        {id: '103',
          authName:'权限管理',
          path:null,
          children: [
            {
              id: '10301',
              authName:'权限列表',
              path:null,
              children: [
                {
                  id: '1030101',
                  authName:'添加权限',
                  path:null
                }
              ]
            }
          ],
        }
      ]
    },
    {
      id:'2',
      roleName:'订单权限',
      roleDesc:'对订单进行管理',
      children:[
        {
          id: '101',
          authName:'商品管理',
          path:null,
          children: [
            {
              id: '10101',
              authName:'商品列表',
              path:null,
              children: [
                {
                  id: '1010101',
                  authName:'添加商品',
                  path:null
                }
              ]
            }
          ]
        }
      ]
    },{
      id:'2',
      roleName:'订单权限',
      roleDesc:'对订单进行管理',
      children:[
        {
          id: '101',
          authName:'商品管理',
          path:null,
          children: [
            {
              id: '10101',
              authName:'商品列表',
              path:null,
              children: [
                {
                  id: '1010101',
                  authName:'添加商品',
                  path:null
                }
              ]
            }
          ]
        }
      ]
    }]
  const temprightsList=[
    {
      id: '101',
      authName: '商品管理',
      path: null,
      pid:'',
      children: [
        {
          id: '10101',
          authName: '商品列表',
          path: null,
          pid:'101',
          children: [
            {
              id: '1010101',
              authName: '添加商品',
              path: null
            }, {
              id: '1010102',
              authName: '修改商品',
              path: null
            }, {
              id: '1010103',
              authName: '删除商品',
              path: null
            }, {
              id: '1010104',
              authName: '商品状态更新',
              path: null
            }
          ]
        },{
          id: '10102',
          authName: '商品分类',
          path: null,
          pid:'101',
          children: [
            {
              id: '1010201',
              authName: '分类管理',
              path: null
            }
          ]
        },{
          id: '10103',
          authName: '商品参数',
          path: null,
          pid:'101',
          children: [
            {
              id: '1010301',
              authName: '参数管理',
              path: null
            }
            ]
        }]
    },
    {
      id: '102',
      authName:'订单管理',
      path:null,
      pid:'',
      children: [
        {
          id: '10201',
          authName:'订单列表',
          path:null,
          pid:'102',
          children: [
            {
              id: '1020101',
              authName:'添加订单',
              path:null
            }
          ]
        }
      ]
    },
    {
      id: '103',
      authName:'权限管理',
      path:null,
      pid:'',
      children: [
        {
          id: '10301',
          authName:'权限列表',
          path:null,
          pid:'103',
          children: [
            {
              id: '1030101',
              authName:'添加权限',
              path:null
            }
          ]
        }
      ]
    }
  ]

  export default {
    name: "Roles",
    data(){
      return {
        //  获取用户列表的参数对象
        queryInfo:{
          query: '',
          //当前在页码
          pageNum: 1,
          //当前每页显示多少条相间
          pageSize: 3
        },
        //所有角色列表数据
        roleList:[],
        //所有权限菜单数据
        rightsList:[],
        //树被选中的数组
        defKeys:[],
        defaultProps: {
          children: 'children',
          label: 'authName'
        },
        total:0,
        //控制添加权限的显示和隐藏
        addDialogVisible: false,
        //分配权限对话框
        setRightDialogVisible: false,
        //添加权限的表单数据
        addForm:{
          rolename:'',
          roledesc:''
        },
        //添加用户表单的验证用户对象
        addFormRules: {
          rolename:[
            {required: true,message:'请输入角色名称',trigger:'blur'}
          ],
          roledesc:[
            {required: true,message:'请输入角色描述',trigger:'blur'}
          ]
        }
      }
    },
    created(){
      this.getRoleList()
    },
    methods: {
      async showSetRightDialog(role){
        this.rightsList=temprightsList
        //获取拥有菜单的三级菜单权限
        this.defKeys=[]
        this.getLeafKey(role,this.defKeys);
        console.log(role)
        console.log(this.defKeys)
        this.setRightDialogVisible=true

        return
        //获取所有权限数据（所有菜单）
        const {data:res}=await this.$http.get(`rights/tree`);
        if (res.meta.status!==200){
          return this.$message.info("获取权限数据失败")
        }
        //赋值
        this.rightsList=res.data;

        this.setRightDialogVisible=true
      },
      //根据id删除对应的权限
      async removeRightById(role,rightId){
        const confirmResult=await
          this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmResult!=='confirm'){
          return this.$message.info("取消了删除,role.id="+role.id+"rightId="+rightId);
        }
        //开始删除
        const {data:res}=await this.$http.delete(`roles/${role.id}/rights/rightId`)
        if(res.meta.state!==200){
          return this.$message.info("删除权限失败")
        }
        //重新获取权限列表
        // this.getRoleList();这种情况会引起页面重新刷新
        //因为dele返回参数会data的新值，所以对role中的children重新赋值即可。
        role.children=res.data;

        // this.$message.info("确认了删除");
      },
      //权限列表
      async getRoleList() {
        this.roleList=temproleList
        this.total=5
        return

        const {data: res} = await this.$http.get('roles',{
          params: this.queryInfo
        })
        if(res.meta.status !=200){
          return this.$message.error('获取角色列表失败')
        }

        this.roleList=res.data.roles
        this.total=res.data.total

        console.log(res);
      },
      //监听pagesize改变事件
      handleSizeChange(newSize) {
        console.log(`每页 ${val} 条`);
        this.queryInfo.pageSize=newSize
        this.getUserList()
      },
      //监听页码值改变的事件
      handleCurrentChange(newPageNum) {
        console.log(`当前页: ${val}`);
        this.queryInfo.pageNum=newPageNum
        this.getUserList()
      },
    //  获取所有权限中的明细节点,通过递归方式，获取三级
    //  并保存在defKeys中
      getLeafKey(node,arr){
      //  如果当前node节点，不包含chilren属性，
        if(!node.children){
          return arr.push(node.id)
        }
        node.children.forEach(item =>{
          this.getLeafKey(item,arr)
        })
      },
      // 监听分配权限对话框关闭事件
      clearRightsKey() {
        // 清空 rightskey 数组
        this.defKeys = [];
      },
    }
  }
</script>

<style lang="less" scoped>
  .el-tag{
    margin: 7px;
  }
  .bdtop{
    border-top: 1px solid #eeeeee;
  }
  .bdbottom{
    border-bottom: 1px solid #eeeeee;
  }

  .vcenter{
    display: flex;
    align-items: center;
  }
</style>
